/** @format */

import { _decorator, Camera, Component, Node, v3, Vec3 } from "cc";
import { app } from "../../../FrameWork/App";
import { gameDataMgr } from "../../_Common/Manager/GameDataManager";
const { ccclass, property } = _decorator;

@ccclass("MainCamera")
export class MainCamera extends Component {
    @property({ displayName: "横向跟随" })
    followX: boolean = false;
    @property({ displayName: "纵向跟随" })
    followY: boolean = false;
    @property({ displayName: "锁定宽度" })
    lockWidth: number = 100;
    @property({ displayName: "锁定高度" })
    lockHeight: number = 100;
    @property({ displayName: "横向减缓系数" })
    slowRateX: number = 0.4;
    @property({ displayName: "纵向减缓系数" })
    slowRateY: number = 0.4;

    nodeTarget: Node = null;

    private _lastPos: Vec3 = null;

    private _left = 0;
    private _bottom = 0;

    private _pos: Vec3 = v3();

    onLoad(): void {
        this._lastPos = this.node.position;
        this._pos = this.node.position;
        gameDataMgr.mainCamera = this;
    }

    update(dt: number) {
        if (!this.nodeTarget) return;
        this._followX(dt);
        this._followY(dt);
    }

    private _followX(dt: number): void {
        if (!this.followX) {
            return;
        }
        let targetPos = this.nodeTarget.position;
        let dis = Math.abs(this._pos.x - targetPos.x);
        if (dis <= this.lockWidth) {
            return;
        }
        let deltaX = targetPos.x - this._pos.x;
        this._pos.x += deltaX * dt * (dis / this.lockWidth) * this.slowRateX;
        this.node.setPosition(this._pos);
        if (this.node.position.x <= this._left) {
            this._pos.x = this._left;
            this.node.position = this._pos;
        }
    }

    private _followY(dt: number): void {
        if (!this.followY) {
            return;
        }
        let targetPos = this.nodeTarget.position;
        let dis = Math.abs(this._pos.y - targetPos.y);
        if (dis <= this.lockHeight) {
            return;
        }
        let deltaY = targetPos.y - this._pos.y;
        this._pos.y += deltaY * dt * (dis / this.lockHeight) * this.slowRateY;
        this.node.setPosition(this._pos);
        if (this.node.position.y <= this._bottom) {
            this._pos.y = this._bottom;
            this.node.position = this._pos;
        }
    }
}
